package cn.mothin.action;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import cn.mothin.frame.bean.ActionResult;
import cn.mothin.frame.core.base.BaseAction;
import cn.mothin.frame.core.interfaces.ILoginUser;
import cn.mothin.frame.help.Password;
import cn.mothin.service.LoginService;
import cn.mothin.vo.LoginForm;

@SuppressWarnings("serial")
public class LoginAction extends BaseAction {
	private LoginForm loginForm = new LoginForm();
	@Autowired
	private LoginService loginService;

	@Override
	public Object getModel() {
		return loginForm;
	}

	public String execute() {
		if (null == this.getLoginUserInfomation()) {
			loginForm.setMd5Time(Password.MD5TIME);
			return SUCCESS;
		}
		return redirectTo("main");
	}

	/**
	 * 随机值
	 * 
	 * @return
	 */
	public String queryRandom() {
		String random = saveRandomKeyInSession();
		ActionResult actionResult = ActionResult.getInstance();
		actionResult.setValue(random);
		return renderJson(actionResult.toJson());
	}

	/**
	 * 登录验证
	 * 
	 * @return
	 */
	public String authentication() {
		ActionResult actionResult = ActionResult.getInstance();
		if (null == getLoginUserInfomation()) {
			Object obj = loginService.authentication(loginForm,
					getRandomKeyInSession(), getRemoteAddress());
			if (obj == null) {
				actionResult.setMessage("帐号或者密码输入不正确");
				actionResult.setOk(false);
			} else {
				if (obj instanceof String) {
					actionResult.setMessage((String) obj);
					actionResult.setOk(false);
				} else {
					ILoginUser loginUser = (ILoginUser) obj;
					saveLoginUserInfomation(loginUser);
					Map<String,Object> map=new HashMap<String,Object>();
					map.put("name", loginUser.getName());
					map.put("superUser", loginUser.isSuperUser());
					actionResult.setValue(map);
				}
			}
		}
		return renderJson(actionResult.toJson());
	}

	public String register() {
		boolean result = loginService.addUser(loginForm);
		ActionResult actionResult = ActionResult.getInstance();
		actionResult.setOk(result);
		if (!result) {
			actionResult.setMessage("用户已存在");
		}
		return renderJson(actionResult.toJson());
	}
}
